package org.dizena.modules.base.service.impl;

import org.dizena.common.db.ByPageQuery;
import org.dizena.common.pojo.PageReq;
import org.dizena.common.pojo.PageResp;
import org.dizena.modules.base.bean.BaseConfig;
import org.dizena.modules.base.dao.BaseConfigDao;
import org.dizena.modules.base.service.BaseConfigService;
import org.dizena.utils.IdGen;
import org.dizena.utils.RedisUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BaseConfigServiceImpl implements BaseConfigService
{

    @Resource
    private BaseConfigDao dao;
    @Resource
    private RedisUtil<BaseConfig> redisUtil;

    @Override
    public String getConfigByKey(String key)
    {
        BaseConfig rm = redisUtil.get("base:config:key:" + key);
        if (rm == null)
        {
            rm = dao.findOne("key", key);
            if (rm != null)
            {
                redisUtil.add("base:config:key:" + key, rm, 300);
                return rm.getValue();
            }
        }
        throw new RuntimeException("base config key " + key + " value is null");
    }

    @Override
    public PageResp<BaseConfig> list(PageReq req)
    {
        ByPageQuery<BaseConfig> byPageQuery = new ByPageQuery<>(req);
        long count = dao.count(byPageQuery);
        List<BaseConfig> list = dao.find(byPageQuery);
        return new PageResp<>(req.getPage(), req.getSize(), count, list);
    }

    @Override
    public void add(BaseConfig m)
    {
        m.setId(IdGen.get().nextSid());
        m.setCreateTime(System.currentTimeMillis());
        dao.insert(m);
        //redis
        redisUtil.add("base:config:key:" + m.getKey(), m, 300);
    }

    @Override
    public void del(String key)
    {
        dao.deleteByKey(key);
        redisUtil.delete("base:config:key:" + key);
    }

    @Override
    public void edit(BaseConfig m)
    {
        BaseConfig old = dao.findOne(m.getId());
        redisUtil.delete("base:config:key:" + old.getKey());
        dao.update(m);
        redisUtil.add("base:config:key:" + m.getKey(), m, 300);
    }

    @Override
    public void add(String key, String value, String description)
    {
        BaseConfig m = dao.findOne("key", key);
        if (null == m)
        {
            m = new BaseConfig();
            m.setId(IdGen.get().nextSid());
            m.setKey(key);
            m.setValue(value);
            m.setCreateTime(System.currentTimeMillis());
            m.setDescription(description);
            dao.insert(m);
        }
        //redis
        redisUtil.add("base:config:key:" + m.getKey(), m, 300);
    }
}
